package com.lvhx.java8;

import lombok.var;
import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

public class LocalDateTest {

    /**
     * ISO标准日历格式日期
     */
    @Test
    public void test1(){
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println(dateTime);

        LocalDate date = LocalDate.now();
        System.out.println(date);

        LocalTime time = LocalTime.now();
        System.out.println(time);

    }

    /**
     * //计算时间差
     */
    @Test
    public void test2(){
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime now2 = LocalDateTime.of(2017, 1, 1, 12, 12, 12);
        Duration duration = Duration.between(now,now2);
        System.out.println(duration.toDays());

        long between = ChronoUnit.YEARS.between(now, now2);
        System.out.println(Integer.valueOf((int) between));
    }

    /**
     * 时间矫正器
     */
    @Test
    public void test3(){

        LocalDateTime now = LocalDateTime.now();
        //这个月第2个星期一
        LocalDateTime with = now.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.MONDAY));
        System.out.println(with);

        //上个月最后一个星期五
        LocalDateTime with1 = now.with(TemporalAdjusters.dayOfWeekInMonth(0, DayOfWeek.FRIDAY));
        System.out.println(with1);

        //这个月倒数第2个周一
        LocalDateTime with2 = now.with(TemporalAdjusters.dayOfWeekInMonth(-2, DayOfWeek.MONDAY));
        System.out.println(with2);


        //下一个也是周五的日期，包括当前日期
        LocalDate localDate = LocalDate.of(2018, 01, 01);
        LocalDate with3 = localDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));


        // 上一个也是周日的日期，包括当前日期。
        LocalDate with8 = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
        System.out.println(with8);

        //自定义,TemporalAdjuster是一个函数式接口
        localDate.with(d -> {
            LocalDateTime l1 = (LocalDateTime) d;
           return l1.plusDays(1);
        });


    }

    /**
     * 格式化日期
     */
    @Test
    public void test4(){
        LocalDate parse = LocalDate.parse("2018-01-01");
        System.out.println(parse);

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse1 = LocalDateTime.parse("2018-01-01 12:12:12", dateTimeFormatter);
        System.out.println(parse1);

        //

    }
}
